import React, { useEffect, useState } from "react";
import { Input, Card, Row, Col, Spin, Empty } from "antd";
import axios from "axios";

const { Search } = Input;

function Warehouse() {
  const [games, setGames] = useState([]);
  const [filteredGames, setFilteredGames] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchGames();
  }, []);

  const fetchGames = async () => {
    try {
      const response = await axios.get("/api/games"); // 根据你的后端路径调整
      setGames(response.data);
      setFilteredGames(response.data);
    } catch (error) {
      console.error("获取游戏失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const onSearch = (value: any) => {
    const filtered = games.filter((game: any) =>
      game.name.toLowerCase().includes(value.toLowerCase())
    );
    setFilteredGames(filtered);
  };

  return (
    <div className="warehouse-page" style={{ padding: "24px" }}>
      <h1
        style={{ fontSize: "24px", fontWeight: "bold", marginBottom: "16px" }}
      >
        游戏仓库
      </h1>

      <Search
        placeholder="搜索游戏名称"
        allowClear
        enterButton="搜索"
        size="large"
        onSearch={onSearch}
        style={{ marginBottom: "24px", maxWidth: "400px" }}
      />

      {loading ? (
        <Spin tip="加载中..." />
      ) : filteredGames.length === 0 ? (
        <Empty description="暂无游戏数据" />
      ) : (
        <Row gutter={[16, 16]}>
          {filteredGames.map((game: any) => (
            <Col xs={24} sm={12} md={8} lg={6} key={game.id}>
              <Card
                hoverable
                cover={
                  <img
                    alt={game.name}
                    src={game.coverImage}
                    style={{ height: 200, objectFit: "cover" }}
                  />
                }
              >
                <Card.Meta
                  title={game.name}
                  description={game.genre || "未知类型"}
                />
              </Card>
            </Col>
          ))}
        </Row>
      )}
    </div>
  );
}

export default Warehouse;
